package com.eastdigit.util;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Release {

    public static void main(String[] args) throws Exception {
        // String projectPath = System.getProperty("user.dir");
        // copyResourcesRecursively(Release.class.getClass().getResource("/"),
        // new File(projectPath + "/src/main/webapp/")); // 复制classpath中的资源到目录
        String jarPath = "D:\\workspace\\framework\\target\\framework.jar";
        String dir = "D:\\workspace\\framework\\target\\resources\\";
        release(jarPath, dir, "underscore-min.js");

        String projectPath = System.getProperty("user.dir");
        jarPath = Release.class.getClass().getResource("/").toString().replace("classes", "lib") + "framework.jar";
        System.out.println(projectPath + "/src/main/webapp/");
        System.out.println(jarPath);
    }

    public static void releaseDefalut(String... ignore) throws IOException {
        String projectPath = System.getProperty("user.dir");
        String jarPath = Release.class.getClass().getResource("/").toString().replace("classes", "lib")
                + "framework.jar";
        release(jarPath.replace("file:/", ""), projectPath + "/src/main/webapp/");
    }

    /**
     * 从jar中获取指定名称的文本文件
     * 
     * @param jarPath
     * @throws IOException
     */
    public static void release(String jarPath, String savePath, String... ignore) throws IOException {
        JarFile jf = new JarFile(jarPath);
        Enumeration<JarEntry> jfs = jf.entries();
        String resources = "META-INF/resources/";
        outer: while (jfs.hasMoreElements()) {
            JarEntry jfn = jfs.nextElement();
            String name = jfn.getName();
            if (name.startsWith(resources)) {
                if (name.endsWith("/")) {
                    File dirFile = new File(savePath + name.replace(resources, ""));
                    if (!dirFile.exists()) {
                        dirFile.mkdirs();
                    }
                } else {
                    if (ignore != null) {
                        for (int i = 0; i < ignore.length; i++) {
                            if (name.endsWith(ignore[i])) {
                                System.out.println("忽略文件:" + name);
                                break outer;
                            }
                        }
                    }
                    InputStream is = jf.getInputStream(jfn);
                    FileUtils.copyInputStreamToFile(is, new File(savePath + name.replace(resources, "")));
                }
            }
        }
    }
}
